package io;

import java.io.*;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description: 实现复制文件, 把一个文件里的每个字节都读出来，写到另一个文件中
 * User: Li_yizYa
 * Date: 2025/5/8
 * Time: 18:54
 */
public class Practice2 {
    public static void main(String[] args) {
        // 1. 输入路径，并做校验
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入源文件路径: ");
        String srcPath = scanner.next();
        File srcFile = new File(srcPath);
        if (!srcFile.isFile()) {
            System.out.println("源文件路径错误!");
            return;
        }
        System.out.print("请输入目标文件路径: ");
        String destPath = scanner.next();
        File destFile = new File(destPath);
        if (!destFile.getParentFile().isDirectory()) {
            System.out.println("目标文件路径有误!");
            return;
        }

        // 2. 执行复制过程
        try (InputStream inputStream = new FileInputStream(srcFile);
             OutputStream outputStream = new FileOutputStream(destFile)) {
            while (true) {
                byte[] buffer = new byte[1024];
                int n = inputStream.read(buffer);
                if (n == -1) {
                    // 读取结束
                    break;
                }
                // 需要把 buffer 写入 outputStream 中
                outputStream.write(buffer, 0, n);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
